package com.ktgj.file.service;

import com.ktgj.common.core.utils.ExcelUtils;
import com.ktgj.file.utils.MinioUtil;
import com.sun.corba.se.impl.protocol.MinimalServantCacheLocalCRDImpl;
import io.minio.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.ktgj.file.config.MinioConfig;
import com.ktgj.file.utils.FileUploadUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */
@Service("MinioSysFileServiceImpl")
public class MinioSysFileServiceImpl implements ISysFileService {
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioClient client;

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public List<String> uploadFile(MultipartFile[] file, String source, String business) throws Exception {
        List<String> urls = new ArrayList<>();
        for (MultipartFile multipartFile : file) {
            String fileName = FileUploadUtils.extractFilename(multipartFile);
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(source + "/" + business + "/" + fileName)
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType())
                    .build();
            client.putObject(args);
            String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + source + "/" + business + "/" + fileName;
            urls.add(url);
        }

        return urls;
    }

    @Value("${file.document-avatar}")
    private String uploadDocument;
    @Value("${file.upload-avatar}")
    private String upload;
    @Value("${file.customer-avatar}")
    private String uploadCustomer;
    @Value("${file.employee-avatar}")
    private String uploadEmployee;
    @Value("${file.workOrder-avatar}")
    private String uploadWorkOrder;
    @Value("${file.airport-avatar}")
    private String uploadAirport;
    @Value("${file.model-avatar}")
    private String uploadModel;
    @Value("${file.VIPHall-avatar}")
    private String uploadVIPHall;
    @Value("${file.mall-avatar}")
    private String uploadMall;
    @Value("${file.combo-avatar}")
    private String uploadCombo;
    @Value("${file.claim-avatar}")
    private String uploadClaim;
    @Value("${file.travel-avatar}")
    private String uploadTravel;
    @Value("${file.hotel-avatar}")
    private String uploadHotel;

    /**
     * 上传头像
     * */
    @Override
    public List<String> uploadAvatar(List<MultipartFile> file, String type) throws Exception {
        List<String> fileList = new ArrayList<>();
        String avatar;
        for (MultipartFile multipartFile : file) {
            String fileName = FileUploadUtils.extractFilename(multipartFile);
            //会员头像
            if (type.equals("customer")){
                avatar = uploadCustomer;
            }
            //工单图片
            else if (type.equals("workOrder")){
                avatar = uploadWorkOrder;
            }
            //机场图片
            else if (type.equals("model")){
                avatar = uploadAirport;
            }
            //机型图片
            else if (type.equals("airport")){
                avatar = uploadModel;
            }
            //贵宾厅
            else if (type.equals("VIPHall")){
                avatar = uploadVIPHall;
            }
            else if (type.equals("mall")){
                avatar = uploadMall;
            }
            else if (type.equals("combo")){
                avatar = uploadCombo;
            }
            else if (type.equals("claim")){
                avatar = uploadClaim;
            }
            else if (type.equals("travel")){
                avatar = uploadTravel;
            }
            else if (type.equals("hotel")){
                avatar = uploadHotel;
            }
            //员工头像
            else {
                avatar = uploadEmployee;
            }
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
//                    .object(upload + "/" + avatar + "/" + fileName)
                    .object(avatar + "/" + fileName)
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType())
                    .build();
            client.putObject(args);
            fileList.add(minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + avatar + "/" + fileName);
        }

        return fileList;
    }

    /**
     * 航司LogoUrl
     * */
    @Override
    public String airlineLogo() {
        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/appResource/airliner/";
    }

    /**
     * 上传文件到服务器
     * @param file 文件流
     * @return
     */
    @Override
    public File document(MultipartFile file) {
        String destFilePath = uploadDocument;
//        String destFilePath = "D:\\ktgj\\FlightAdjust";
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            String fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            inputStream = file.getInputStream();
            // 数据缓冲
            byte[] buffer = new byte[1024 * 1024];
            //读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(destFilePath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            //重新命名
            fileName = UUID.randomUUID().toString() +"."+ split[split.length-1];
            fileOutputStream = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
            return tempFile;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                fileOutputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Value("${minio.bucketName}")
    private String bucketName;

    @GetMapping
    public void downloadFiles(@RequestParam("filename") String filename, HttpServletResponse httpResponse) {
        try {
//            MinioClient minioClient = minioConfig.getMinioClient();
            InputStream object = minioUtil.getObject(bucketName, filename);
            byte buf[] = new byte[1024];
            int length = 0;
            httpResponse.reset();
            httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            httpResponse.setContentType("application/octet-stream");
            httpResponse.setCharacterEncoding("utf-8");
            OutputStream outputStream = httpResponse.getOutputStream();
            while ((length = object.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.close();
        } catch (Exception ex) {
            ex.getMessage();
        }
    }
}
